/*
========================================================================
 Name        : ExportContactsListBox.cpp
 Author      : etouch.cc
 Copyright   : etouch.cc,All Right Reserved!
 Description : 
========================================================================
*/

#include <barsread.h>
#include <stringloader.h>
#include <aknlists.h>
#include <eikenv.h>
#include <akniconarray.h>
#include <eikclbd.h>
#include <aknviewappui.h>
#include <eikappui.h>
#include <ExportContacts.rsg>
#include <aknquerydialog.h> 

#include "ExportContactsListBox.h"
#include "ExportContactsListBoxView.h"
#include "ExportContacts.hrh"
#include "ExportContactsListBox.hrh"
#include "ExportContactsSelectDirContainer.hrh"
#include "ContactEngine.h" 
#include "Contact.h"

_LIT(KSpalsh,"#");

CExportContactsListBox::CExportContactsListBox()
{
	iContactListBox = NULL;
	iContactEngine = NULL;	
}
 
CExportContactsListBox::~CExportContactsListBox()
{	 
	delete iContactListBox;
	iContactListBox = NULL;	
}
				
 
CExportContactsListBox* CExportContactsListBox::NewL( const TRect& aRect, 
													  const CCoeControl* aParent, 
													  MEikCommandObserver* aCommandObserver 
													 )
{
	CExportContactsListBox* self = CExportContactsListBox::NewLC( 
																 aRect, 
																 aParent, 
																 aCommandObserver 
																 );
	CleanupStack::Pop( self );
	return self;
}

 
CExportContactsListBox* CExportContactsListBox::NewLC( 
														const TRect& aRect, 
														const CCoeControl* aParent, 
														MEikCommandObserver* aCommandObserver 
													  )
{
	CExportContactsListBox* self = new ( ELeave ) CExportContactsListBox();
	CleanupStack::PushL( self );
	self->ConstructL( aRect, aParent, aCommandObserver );
	return self;
}
			
 
void CExportContactsListBox::ConstructL( const TRect& aRect, 
										 const CCoeControl* aParent, 
										 MEikCommandObserver* aCommandObserver )
{
	if ( aParent == NULL )
	{
		CreateWindowL();
	}
	else
	{
	    SetContainerWindowL( *aParent );
	}
	iFocusControl = NULL;
	iCommandObserver = aCommandObserver;
	InitializeControlsL();
	SetRect( aRect );
	ActivateL();	
}
			
 
TInt CExportContactsListBox::CountComponentControls() const
{
	return ( int ) ELastControl;
}
				
 
CCoeControl* CExportContactsListBox::ComponentControl( TInt aIndex ) const
{	 
	switch ( aIndex )
	{
		case EFileSelectListBox:
		return iContactListBox;
	}
	return NULL;
}
				
 				
void CExportContactsListBox::SizeChanged()
{
	CCoeControl::SizeChanged();
	LayoutControls(); 
	
}			
void CExportContactsListBox::SetContactEngine(ContactEngine* aContactEngine)
{
	iContactEngine = aContactEngine;
}

void CExportContactsListBox::LayoutControls()
{
	iContactListBox->SetExtent( TPoint( 0, 0 ), iContactListBox->MinimumSize() );
}

void CExportContactsListBox::HandlePointerEventL(const TPointerEvent& aPointerEvent)
{	 
	CCoeControl::HandlePointerEventL(aPointerEvent);
}		

TKeyResponse CExportContactsListBox::OfferKeyEventL( const TKeyEvent& aKeyEvent,TEventCode aType )
{
	 
	if ( aKeyEvent.iCode == EKeyLeftArrow 
		|| aKeyEvent.iCode == EKeyRightArrow )
	{  
		return EKeyWasNotConsumed;
	}	
	if ( iFocusControl != NULL
		&& iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed )
	{
		return EKeyWasConsumed;
	}
	return CCoeControl::OfferKeyEventL( aKeyEvent, aType );
}				
 				
void CExportContactsListBox::InitializeControlsL()
{
	iContactListBox = new ( ELeave ) CAknDoubleStyle2ListBox;
	iContactListBox->SetContainerWindowL( *this );
	{
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_EXPORT_CONTACTS_LIST_BOX_FILE_SELECT_LIST_BOX );
		iContactListBox->ConstructFromResourceL( reader );
		CleanupStack::PopAndDestroy();  
	}
	 
	iContactListBox->Model()->SetOwnershipType( ELbmOwnsItemArray );	 
	
	SetupFileSelectListBoxIconsL();	 
	
	iContactListBox->SetFocus( ETrue );
	iFocusControl = iContactListBox;	
	iContactListBox->CreateScrollBarFrameL( ETrue );
	iContactListBox->ScrollBarFrame()->SetScrollBarVisibilityL(CEikScrollBarFrame::EOff, CEikScrollBarFrame::EAuto );	
}
 
void CExportContactsListBox::FillListBoxWithContacts()
{
	if(iContactEngine)
	{
		TInt pCount = iContactEngine->GetContactCount();
		if(pCount>0)
		{
			TBuf<512> listString; 
			for(TInt item=0;item<pCount;item++)
			{
				Contact* pTempContact = iContactEngine->GetContactByIndex(item);
				if(pTempContact)
				{
					listString.Zero();
					TDesC&  pFamilyName = pTempContact->GetContactFieldByIndex(KFirstNameIndex);
					TDesC&  pGivenName = pTempContact->GetContactFieldByIndex(KGivenNameIndex);
					
					HBufC* pFullName = HBufC::NewL(pFamilyName.Length()+pGivenName.Length());
					TPtr ptr(pFullName->Des());
					
					ptr.Append(pFamilyName);
					ptr.Append(pGivenName);				
 
					HBufC* pPhoneBuf = NULL;				
					for(TInt item = 0;item<3;item++)
					{
						TDesC& pPhone = pTempContact->GetContactFieldByIndex(KMobileIndex + item);
						if(pPhone.Length()>0)
						{
							TInt spalshPos = -1;
							spalshPos = pPhone.Find(KSpalsh);
							if(spalshPos < 0)
							{
								pPhoneBuf = HBufC::NewL(pPhone.Length());
								TPtr   phonePtr(pPhoneBuf->Des());
								phonePtr.Append(pPhone);
							}else 
							{
								pPhoneBuf = HBufC::NewL(pPhone.Left(spalshPos).Length());
								TPtr   phonePtr(pPhoneBuf->Des());
								phonePtr.Append(pPhone.Left(spalshPos));
							}
							break;
						}						
					}
					if(pPhoneBuf)
					{
						CreateFileSelectListBoxItemL(listString,*pFullName,*pPhoneBuf);
						delete pPhoneBuf;
					}else
					{
						CreateFileSelectListBoxItemL(listString,*pFullName,KNullDesC);
					}					
					AddListBoxItemL( iContactListBox, listString );
					delete pFullName;
				}			
			}	
		}		
	}
}
TInt CExportContactsListBox::RunDeleteQurryL( const TDesC* aOverrideText )
{				
	CAknQueryDialog* queryDialog = CAknQueryDialog::NewL();		
	if ( aOverrideText != NULL )
	{
		queryDialog->SetPromptL( *aOverrideText );
	}else 
	{
		HBufC* pMessageText = StringLoader::LoadL(R_EXPORT_CONTACTS_EXPORTING_CONTAINER_MESSAGE_DELETE_MESSAGE);
		queryDialog->SetPromptL( *pMessageText );
		delete pMessageText;
	}
	return queryDialog->ExecuteLD( R_EXPORT_CONTACTS_EXPORTING_CONTAINER_CONF_QUERY1 );
}

void CExportContactsListBox::DeleteSelectedContact()
{
	CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( iContactListBox->Model() );
	TInt pCount = model->NumberOfItems();
	if (  pCount == 0 )
	{
		return ;
	}
	else 
	{
		if(RunDeleteQurryL(NULL))
		{
			TInt pSelectedIndex = iContactListBox->CurrentItemIndex();
			CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
			TInt currentItem = 0;
			itemArray->Delete ( pSelectedIndex );
			AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(iContactListBox, currentItem, ETrue );
			
			if(iContactEngine)
			{
				iContactEngine->DeleteContact(pSelectedIndex);
			}
		}	
	}
}
TInt CExportContactsListBox::ListBoxItemCount()
{
	CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( iContactListBox->Model() );
	TInt pCount = model->NumberOfItems();
	return pCount;
}

void CExportContactsListBox::HandleResourceChange( TInt aType )
{
	CCoeControl::HandleResourceChange( aType );
	SetRect( iAvkonViewAppUi->View( TUid::Uid( EExportContactsListBoxViewId ) )->ClientRect() );
}
 				
void CExportContactsListBox::Draw( const TRect& aRect ) const
{ 
	CWindowGc& gc = SystemGc();
	gc.Clear( aRect );	
}		
 
void CExportContactsListBox::AddListBoxItemL( CEikTextListBox* aListBox,
											  const TDesC& aString )
{
	CTextListBoxModel* model = aListBox->Model();
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	itemArray->AppendL( aString );
	aListBox->HandleItemAdditionL();
}
 
RArray< TInt >* CExportContactsListBox::GetSelectedListBoxItemsLC( CEikTextListBox* aListBox )
{
	CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
	{
		return NULL;
	}	 
	const CListBoxView::CSelectionIndexArray* selectionIndexes = aListBox->SelectionIndexes();
	TInt selectedIndexesCount = selectionIndexes->Count();
	if ( selectedIndexesCount == 0 )
	{
		return NULL;
	} 
	RArray<TInt>* orderedSelectedIndices = 	new (ELeave) RArray< TInt >( selectedIndexesCount );	 
	CleanupStack::PushL( orderedSelectedIndices );	 
	CleanupClosePushL( *orderedSelectedIndices );	 
	CAknListBoxFilterItems* filter = model->Filter();
	if ( filter != NULL )
	{		 
		for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
		{
			TInt filteredItem = ( *selectionIndexes ) [ idx ];
			TInt actualItem = filter->FilteredItemIndex ( filteredItem );
			orderedSelectedIndices->InsertInOrder( actualItem );
		}
	}
	else
	{
		 
		for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
			orderedSelectedIndices->InsertInOrder( ( *selectionIndexes ) [ idx ] );
	}			
	return orderedSelectedIndices;
}
 
void CExportContactsListBox::DeleteSelectedListBoxItemsL( CEikTextListBox* aListBox )
{
	CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
	{
		return;
	}	
	RArray< TInt >* orderedSelectedIndices = GetSelectedListBoxItemsLC( aListBox );		
	if ( !orderedSelectedIndices )
	{
		return;
	}	 
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	TInt currentItem = 0;
	
	for ( TInt idx = orderedSelectedIndices->Count(); idx-- > 0; ) 
	{
		currentItem = ( *orderedSelectedIndices )[ idx ];
		itemArray->Delete ( currentItem );
	}	 
	CleanupStack::PopAndDestroy();	
	CleanupStack::PopAndDestroy( orderedSelectedIndices );	
	AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(aListBox, currentItem, ETrue );
}
 
TBool CExportContactsListBox::HandleMarkableListCommandL( TInt aCommand )
{
	return EFalse;
}
 
CAknDoubleStyle2ListBox* CExportContactsListBox::FileSelectListBox()
{
	return iContactListBox;
}
 
void CExportContactsListBox::CreateFileSelectListBoxItemL(  TDes& aBuffer, 
															const TDesC& aMainText,
															const TDesC& aSecondaryText
														  )
{
	_LIT ( KStringHeader, "\t%S\t%S" );	
	aBuffer.Format( KStringHeader(), &aMainText, &aSecondaryText );
} 				
 
void CExportContactsListBox::AddFileSelectListBoxResourceArrayItemL( TInt aResourceId )
{
	CDesCArray* array = iCoeEnv->ReadDesCArrayResourceL( aResourceId );
	CleanupStack::PushL( array );	 
	TBuf<512> listString; 
	CreateFileSelectListBoxItemL( listString, ( *array ) [ 0 ], ( *array ) [ 1 ] );
	AddListBoxItemL( iContactListBox, listString );
	CleanupStack::PopAndDestroy( array );
} 			
 
void CExportContactsListBox::SetupFileSelectListBoxIconsL()
{
	CArrayPtr< CGulIcon >* icons = NULL;	
	if ( icons != NULL )
	{
		iContactListBox->ItemDrawer()->ColumnData()->SetIconArray( icons );
	}
}
//End of file

